# -*- coding:UTF-8 -*-
import requests
import time
import random
import hashlib
from init.socketinit import host as init_host

class SocketHelper(object):

    """description of class"""
    def __init__(self):
        self.urllis="http://"+init_host+"/api/listen?key="
        self.urlreq = "http://"+init_host+"/api/request"
        self.urlrep = "http://"+init_host+"/api/reply?time="
        self.reqkey = str(random.randint(1,10000))

    def listen(self):
        try:
            url = self.urllis+self.reqkey
            message = requests.post(url)
        except:
            return "Null"
        
        return message

    def request(self,data):
        try:
            #print("http://127.0.0.1/api/request==>"+data)
            header = {"Content-Type": "application/x-www-form-urlencoded"}
            message = requests.post(self.urlreq,data=data,headers=header)
        except:
            return "Null"
        finally:
            print(message.text)
        return

    def reply(self,time):
        time+=self.reqkey
        message =  requests.post(self.urlrep+time)
        if(message == "Clear"):
            self.reqkey = str(random.randint(1,10000))

    def set_host(self,host):
        init_host = host
        self.urllis = "http://" + init_host + "/api/listen?key="
        self.urlreq = "http://" + init_host + "/api/request"
        self.urlrep = "http://" + init_host + "/api/reply?time="

    def set_ky(self,key):
        self.reqkey=key